<template>
  <div>
    <ImportData ref='importData'></ImportData>
    <Row>
      <Col span="5" style="padding: 15px 0px;">
        <Input v-model="query.keywords" placeholder="学校名称" style="width: 200px" />
      </Col>
      <Col span="8" style="padding: 15px 0px;">
        <Button @click="load(1)" style="margin-right:15px;" type='success'>筛选</Button>
        <Button @click="clearQuery">清除</Button>
      </Col>
    </Row>
    <Row>
      <Col span="24">
        <Table :columns="columns" :data="items"></Table>
      </Col>
    </Row>
    <Row>
      <Col span="24">
        <div style="text-align:right;margin: 20px 10px;">
          <Page :page-size-opts="[10, 20, 30]" @on-page-size-change="changeLimit" show-sizer @on-change="load" :page-size="query.limit" :current.sync="query.page" :total="total" size="small" />
        </div>
      </Col>
    </Row>
    <Modal
      v-model="renewal_modal.show"
      :title="renewal_form.name + '-续期'"
      :loading="renewal_modal.loading"
      @on-ok="renewal">
      <div>
        <Row style="margin-bottom:15px;">
          <Col span="20" offset="2">
            <Input v-model="renewal_form.day_number" placeholder="请输入大于0的整数">
              <span slot="prepend">续期时间:</span>
              <span slot="append">天</span>
            </Input>
          </Col>
        </Row>
        <Row>
          <Col span="20" offset="2">
            <Input v-model="renewal_form.pay_fee" placeholder="请输入实际费用">
              <span slot="prepend">续期费用:</span>
              <span slot="append">元</span>
            </Input>
          </Col>
        </Row>
      </div>
    </Modal>
    <analyze-modal ref='analyze-modal'></analyze-modal>
  </div>
</template>
<script>
import { fetchSchools } from '@/graphql/query/school'
import { changeSchoolState, renewalSchool } from '@/graphql/mutation/school'
import DefaultSchoolImage from '@/assets/images/default-school.png'

import dayjs from 'dayjs'
import validatejs from 'validate.js'
import ImportData from './components/import-data/index'
import AnalyzeModal from '@/view/operational-data/modal'

export default {
  components: {
    ImportData,
    AnalyzeModal
  },
  data () {
    const self = this
    return {
      renewal_form: {
        id: '',
        name: '',
        pay_fee: null,
        day_number: null
      },
      renewal_modal: {
        show: false,
        loading: true
      },
      total: 0,
      query: {
        limit: 10,
        page: 1,
        keywords: '',
        start_date: '',
        end_date: ''
      },
      columns: [
        {
          title: '序号',
          render: (h, params) => {
            const startNumber = this.query.limit * (this.query.page - 1)
            const { _id, name } = params.row
            const items = []
            items.push(
              h('span', {
              }, startNumber + params.index + 1)
            )
            items.push(
              h('span', {
                style: {
                  color: '#525b6c',
                  marginLeft: '5px',
                  cursor: 'pointer'
                },
                on: {
                  click: () => {
                    self.$refs['analyze-modal'].open(_id, name)
                  }
                },
                class: 'iconfont icon-digital'
              })
            )
            return h('span', items)
          },
          width: 80,
          align: 'center'
        },
        {
          title: '状态',
          width: 120,
          align: 'center',
          render (h, params) {
            const { state, expireTime } = params.row
            let state_text = ''
            if (state === 'new') {
              state_text = '待审核'
            } else if (state === 'available') {
              state_text = '使用中'
              // 判断是否到期
              if (dayjs().isAfter(dayjs(expireTime), 'day')) {
                state_text = '已到期'
              }
            } else if (state === 'freezing') {
              state_text = '停用'
            } else if (state === 'failed') {
              state_text = '已拒绝'
            } else if (state === 'expired') {
              state_text = '已过期'
            } else if (state === 'closed') {
              state_text = '已关闭'
            }
            return h('span', state_text)
          }
        },
        {
          title: '学校名称',
          key: 'name',
          width: 100,
          tooltip: true,
          align: 'center'
        },
        {
          title: '学校logo',
          width: 100,
          render (h, params) {
            let { logo } = params.row
            if (!logo) {
              logo = DefaultSchoolImage
            }
            return h('img', {
              attrs: {
                src: logo
              },
              style: {
                width: '50px',
                height: '50px',
                margin: '10px'
              }
            })
          },
          align: 'center'
        },
        {
          title: '校长',
          render: (h, params) => {
            const { owner } = params.row
            return h('span', owner.name)
          },
          width: 80,
          align: 'center'
        },
        {
          title: '公司名称',
          width: 150,
          tooltip: true,
          key: 'company',
          align: 'center'
        },
        {
          title: '公司电话',
          width: 120,
          key: 'phone'
        },
        {
          title: '申请时间',
          width: 150,
          align: 'center',
          render (h, params) {
            const { created } = params.row
            if (!created) {
              return h('span', '-')
            }
            const date = h('div', dayjs(created).format('YYYY-MM-DD'))
            const time = h('div', dayjs(created).format('HH:mm:ss'))
            return h('div', [date, time])
          }
        },
        {
          title: '开通时间',
          width: 150,
          align: 'center',
          render (h, params) {
            const { firstConfirmTime } = params.row
            if (!firstConfirmTime) {
              return h('span', '-')
            }
            const date = h('div', dayjs(firstConfirmTime).format('YYYY-MM-DD'))
            const time = h('div', dayjs(firstConfirmTime).format('HH:mm:ss'))
            return h('div', [date, time])
          }
        },
        {
          title: '使用天数',
          key: 'customer_name',
          width: 100,
          align: 'center',
          render (h, params) {
            const { firstConfirmTime } = params.row
            if (firstConfirmTime) {
              return h('span', dayjs().startOf('day').diff(dayjs(firstConfirmTime).startOf('day'), 'day'))
            }
            return h('span', '0')
          }
        },
        {
          title: '剩余天数',
          key: 'contact_number',
          width: 100,
          align: 'center',
          render (h, params) {
            const { expireTime, firstConfirmTime } = params.row
            if (!firstConfirmTime) {
              return h('span', 30)
            }
            return h('span', dayjs(expireTime).diff(dayjs(dayjs().format('YYYY-MM-DD 23:59:59')), 'day'))
          }
        },
        {
          title: '操作',
          width: 240,
          align: 'center',
          fixed: 'right',
          render (h, params) {
            const { state, _id, name } = params.row
            const btns = []
            if (state === 'expired') {
              btns.push(h('Button', {
                props: {
                  size: 'small',
                  type: 'success'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click () {
                    self.openRenewalModal(_id, name)
                  }
                }
              }, '续期'))
            } else if (state === 'new') {
              btns.push(h('Button', {
                props: {
                  size: 'small',
                  type: 'success'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click () {
                    self.pass(_id, name)
                  }
                }
              }, '通过'))
              btns.push(h('Button', {
                props: {
                  size: 'small',
                  type: 'default'
                },
                on: {
                  click () {
                    self.faild(_id, name)
                  }
                }
              }, '不通过'))
              return h('span', btns)
            } else if (state === 'available') {
              btns.push(h('Button', {
                props: {
                  size: 'small',
                  type: 'success'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click () {
                    self.importData(_id)
                  }
                }
              }, '数据导入'))
              btns.push(h('Button', {
                props: {
                  size: 'small',
                  type: 'success'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click () {
                    self.openRenewalModal(_id, name)
                  }
                }
              }, '续期'))
              btns.push(h('Button', {
                props: {
                  size: 'small',
                  type: 'error'
                },
                on: {
                  click () {
                    self.close(_id, name)
                  }
                }
              }, '关闭'))
              return h('span', btns)
            } else if (state === 'closed') {
              btns.push(h('Button', {
                props: {
                  size: 'small',
                  type: 'info'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click () {
                    self.open(_id, name)
                  }
                }
              }, '启用'))
              btns.push(h('Button', {
                props: {
                  size: 'small',
                  type: 'warning'
                },
                on: {
                  click () {
                    self.openRenewalModal(_id, name)
                  }
                }
              }, '续期'))
              return h('span', btns)
            } else if (state === 'failed') {
              btns.push(h('Button', {
                props: {
                  size: 'small',
                  type: 'success'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click () {
                    self.pass(_id, name)
                  }
                }
              }, '通过'))
              return h('span', btns)
            }
            return h('span', btns)
          }
        }
      ],
      items: []
    }
  },
  mounted () {
    this.load(1)
  },
  methods: {
    changeLimit (limit) {
      this.query.limit = limit
      this.load(1)
    },
    changeState (school_id, state) {
      changeSchoolState({ input: { school_id, state } }).then((res) => {
        // 弹出信息
        this.$Message.info('更新成功!')
        // 刷新列表
        this.load(this.query.page)
      })
    },
    close (id, name) {
      this.$Modal.confirm({
        title: '关闭确认',
        content: `<p>是否关闭"${name}"使用权限?</p>`,
        onOk: () => {
          this.changeState(id, 'closed')
        },
        onCancel: () => {}
      })
    },
    importData (id) {
      this.$refs.importData.open(id)
    },
    open (id, name) {
      this.$Modal.confirm({
        title: '启用确认',
        content: `<p>是否启用"${name}"学校使用权限?</p>`,
        onOk: () => {
          this.changeState(id, 'available')
        },
        onCancel: () => {}
      })
    },
    renewal () {
      const data = {
        school_id: this.renewal_form.id,
        day_number: parseInt(this.renewal_form.day_number),
        pay_fee: parseInt(this.renewal_form.pay_fee)
      }
      const rules = {
        school_id: {
          presence: {
            allowEmpty: false,
            message: '学校不能为空!'
          }
        },
        day_number: {
          numericality: {
            greaterThan: 0,
            onlyInteger: true,
            notGreaterThan: '天数必须大于0',
            notEven: '续约时间仅能为整数'
          },
          presence: {
            allowEmpty: false,
            message: '续约时间不能为空!'
          }
        },
        pay_fee: {
          numericality: {
            onlyInteger: true,
            notGreaterThanOrEqualTo: '费用必须不能小于0',
            greaterThanOrEqualTo: 0,
            notEven: '支付金额仅能为整数'
          },
          presence: {
            allowEmpty: false,
            message: '支付金额不能为空!'
          }
        }
      }
      const validateResult = validatejs(data, rules, { format: 'flat', fullMessages: false })
      if (validateResult) {
        this.$Message.error(validateResult[0])
        this.renewal_modal.loading = false
        this.$nextTick(() => {
          this.renewal_modal.loading = true
        })
        return true
      }
      data.pay_fee = data.pay_fee * 1000
      // 确认操作
      const school_name = this.renewal_form.name
      this.$Modal.confirm({
        title: '续期确认',
        content: `<p>是否为"${school_name}"续期?</p>`,
        onOk: () => {
          // 发送请求
          this.renewal_modal.loading = true
          renewalSchool({ input: data }).then(() => {
            this.renewal_modal.loading = false
            this.renewal_modal.show = false
            this.$nextTick(() => {
              this.renewal_modal.loading = true
              this.$Message.success('续期成功!')
              this.load(this.query.page)
            })
          }).catch(() => {
            this.renewal_modal.loading = false
            this.$nextTick(() => {
              this.renewal_modal.loading = true
              this.$Message.error('续期失败,请重试!')
            })
          })
        },
        onCancel: () => {
          this.renewal_modal.loading = false
          this.$nextTick(() => {
            this.renewal_modal.loading = true
          })
        }
      })
    },
    openRenewalModal (id, name) {
      this.renewal_form.id = id
      this.renewal_form.name = name
      this.renewal_form.pay_fee = null
      this.renewal_form.day_number = null
      this.renewal_modal.show = true
    },
    pass (id, name) {
      this.$Modal.confirm({
        title: '审核确认',
        content: `<p>是否通过"${name}"审核?</p>`,
        onOk: () => {
          this.changeState(id, 'available')
        },
        onCancel: () => {}
      })
    },
    faild (id, name) {
      this.$Modal.confirm({
        title: '审核确认',
        content: `<p>是否拒绝"${name}"审核?</p>`,
        onOk: () => {
          this.changeState(id, 'failed')
        },
        onCancel: () => {}
      })
    },
    clearQuery () {
      this.query.keywords = ''
      this.query.start_date = ''
      this.query.end_date = ''
      this.load(1)
    },
    load (page) {
      this.query.page = page
      fetchSchools({ input: this.query }).then((res) => {
        const { schools } = res.data
        this.query.page = schools.current_page
        this.query.limit = schools.limit
        this.items = schools.data
        this.total = schools.total
      })
    }
  }
}
</script>
